<?php

namespace App\Services\MakeSeckillOrder;

use App\Models\User;
use App\Models\Order;
use Carbon\Carbon;
use App\Models\Address;
use App\Models\SeckillProduct;
use App\Models\ProductExpress;
use App\Models\ProductSku;
use Illuminate\Support\Facades\Redis;
use App\Http\Controllers\Api\V1\Requests\FormRequest;
use Rainsens\Dinglog\Facades\Dinglog;

class MakeSeckillOrderRequest extends FormRequest
{
	public function rules()
	{

		$addressId =  (int)request('address_id');
		if ($addressId) {
			$this->address = Address::find($addressId);
		}
		return [
			'sid' => [
				'required',
				'integer',
				'min:1',
				$this->seckillProduct(),
			],
			'sku_id' =>  [
				'required',
				'integer',
				'min:1',
				 $this->sku()
			],
			'address_id' => ['required', $this->address()],
			'amount' => [
				'required',
				'integer',
				'min:1'
			]
			
		];
	}

	public function seckillProduct()
	{
		return function ($key, $value, $fail) {

			$sid = $this->sid;
			$seckillProduct = SeckillProduct::find($sid);
			$productExpress = ProductExpress::query()->where('is_allowed',false)->where('product_id',$seckillProduct->product_id)->where('province_code',$this->address->province_code)->first();

			$strat_at = cs("sale")->start_at;
			$end_at = cs("sale")->end_at;
			$time = Carbon::now();

			if (!$seckillProduct) {
				return fail('秒杀商品不存在');
			}elseif ($time->lt(Carbon::parse(date("Y-m-d",time()).' '.$strat_at))
					or $time->gt(Carbon::parse(date("Y-m-d",time()).' '.$end_at))) {

					fail("秒杀时间：每日{$strat_at}~{$end_at}");
				
			/*}elseif($this->user()->isNotValidVip()){
				return fail('非会员不可抢购');*/
			/*}elseif (!SeckillProduct::sIsInSoldCache($sid)) {
				return fail('当前商品已抢光');*/
			}elseif ($productExpress) {
				return fail('地址不在配送范围');
			}elseif($seckillProduct->quota > 0){
				/*$orderNum = $this->user()->orders()->where('sid',$sid)->whereDate('created_at',Carbon::today())->whereNotNull('paid_at')->count();*/

				$orderNum = Redis::get(SeckillProduct::userSeckillCount($this->user()->id,$sid));
				if($orderNum >= $seckillProduct->quota){

					return fail('超过当日限购数量');
				}

			}
			return true;
		};
	}

	public function sku()
	{
		return function ($attribute, $value, $fail) {
			if (!$sku = ProductSku::find($value)) {
				return $fail('此商品不存在');
			} elseif (!$sku->product->is_sale) {
				return $fail('此商品未上架');
			} elseif ($sku->stock === 0) {
				return $fail('此商品已售完');
			} 
			
			$amount = request()->amount;
			if ($amount > 0 and $amount > $sku->stock) {
				return $fail('此商品库存不足');
			}
			return true;
		};
	}

	public function address()
	{
		return function ($attribute, $value, $fail) {
			
			if (!$this->address) {
				return $fail('地址不存在');
			}
			return true;
		};
	}

	public function getAddress(): Address
	{
		return $this->address;
	}

	public function items()
	{
		$item['items'] = [
			'sku_id'=>request()->sku_id,
			'amount'=> request()->amount,
		];
		return $item;


	}

}
